package com.atom.app.mvvm.stack

import android.app.Activity
import androidx.fragment.app.Fragment
import java.util.Stack

object AppStackManager {
    private val activityStack = Stack<Activity?>()
    private val fragmentStack = Stack<Fragment?>()

    fun addActivity(activity: Activity?) {
        activityStack.add(activity)
    }

    fun removeActivity(activity: Activity) {
        activityStack.remove(activity)
    }

    fun isActivity(): Boolean {
        return !activityStack.isEmpty()
    }

    fun currentActivity(): Activity? {
        return activityStack.lastElement()
    }

    fun finishActivity() {
        this.finishActivity(activityStack.lastElement())
    }

    fun finishActivity(activity: Activity?) {
        if (activity != null && !activity.isFinishing) {
            activity.finish()
        }
    }

    fun finishActivity(cls: Class<*>?) {
        for (activity in activityStack) {
            if (activity?.javaClass == cls) {
                this.finishActivity(activity)
                break
            }
        }
    }

    fun finishAllActivity() {
        var i = 0
        val size = activityStack.size
        while (i < size) {
            if (null != activityStack[i]) {
                this.finishActivity(activityStack[i])
            }
            ++i
        }
        activityStack.clear()
    }

    fun getActivity(cls: Class<*>?): Activity? {
        for (activity in activityStack) {
            if (activity?.javaClass == cls) {
                return activity
            }
        }
        return null
    }

    fun addFragment(fragment: Fragment) {
        fragmentStack.add(fragment)
    }

    fun removeFragment(fragment: Fragment?) {
        if (fragment != null) {
            fragmentStack.remove(fragment)
        }
    }

    fun isFragment(): Boolean {
        return !fragmentStack.isEmpty()
    }

    fun currentFragment(): Fragment? {
        return fragmentStack.lastElement()
    }

    fun AppExit() {
        try {
            this.finishAllActivity()
        } catch (var2: Exception) {
            activityStack.clear()
            fragmentStack.clear()
            var2.printStackTrace()
        }
    }
}